#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QFile file(":/css/F:/BassCss.qcss");
    file.open(QFile::ReadOnly);
    QString styleSheet = tr(file.readAll());

    //设置全局样式
    this->setStyleSheet(styleSheet);

    login = new Login();
    login->show();
    connect(login,&Login::loginSingle,this,&MainWindow::dealLogin);
    connect(login,&Login::exitLogin,this,&MainWindow::exitLogin);

    ui->setupUi(this);
    icon.addFile(QStringLiteral(":/img/G:/MaxDatum/mobile/images/logo1.png"), QSize(), QIcon::Normal, QIcon::Off);
    this->setWindowIcon(icon);
    this->setWindowTitle("首页");

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&MainWindow::dealTimeout);
    timer->start(1500);

    //自定义线程（继承Qthread）
    myThread = new MyThread(this);  
    connect(myThread,&MyThread::isDone,this,&MainWindow::updLable);

    //关闭窗口，停止线程
    connect(this,&MainWindow::destroyed,this,&MainWindow::mtRun);

    //websocket进行长连接
    //自动连接 定时器
    qsTimer = new QTimer(this);
    qwebSocket = new QWebSocket();

    connect(qwebSocket,&QWebSocket::disconnected,this,&MainWindow::onDisconnected);
    connect(qwebSocket,&QWebSocket::textMessageReceived,this,&MainWindow::onTextReceived);
    connect(qwebSocket,&QWebSocket::connected,this,&MainWindow::onConnected);
    connect(qsTimer,&QTimer::timeout,this,&MainWindow::reconnect);
    qwebSocket->open(QUrl("ws://localhost:8080/websocket/2"));

    //打印
    QAction *action_print = new QAction(tr("打印"),this);
    QAction *action_printPreview = new QAction(tr("打印预览"),this);
    QAction *action_pdf = new QAction(tr("生成pdf"),this);

    connect(action_print,&QAction::triggered,this,&MainWindow::doPrint);
    connect(action_printPreview,&QAction::triggered,this,&MainWindow::doPrintPreview);
    connect(action_pdf,&QAction::triggered,this,&MainWindow::createPdf);

    ui->mainToolBar->addAction(action_print);
    ui->mainToolBar->addAction(action_printPreview);
    ui->mainToolBar->addAction(action_pdf);       

    view = new QWebEngineView();
    //view->setUrl(QUrl(QStringLiteral("D:/phpstudy_pro/WWW/index.html")));

    handler = new PrintHandler();
}
MainWindow::~MainWindow()
{
    delete ui;
    delete qThread;
}
void MainWindow::exitLogin(){
    this->close();
}

void MainWindow::dealLogin(QString username, QString passward){
    this->show();
    login->close();
    qDebug()<<passward<<username;
    ui->label->setText(QString("欢迎用户:%1").arg(username));
}

void MainWindow::doPrint(){
    // 创建打印机对象
    QPrinter printer;
    // 创建打印对话框
    QPrintDialog dlg(&printer, this);

    //如果编辑器中有选中区域，则打印选中区域
    if (ui->textEdit->textCursor().hasSelection())
        dlg.addEnabledOption(QAbstractPrintDialog::PrintSelection);

    // 如果在对话框中按下了打印按钮，则执行打印操作
    if (dlg.exec() == QDialog::Accepted)
        ui->textEdit->print(&printer);

}
void MainWindow::doPrintPreview(){
   QPrinter printer;
   // 创建打印预览对话框
   QPrintPreviewDialog preview(&printer, this);

   // 当要生成预览页面时，发射paintRequested()信号
   connect(&preview, &QPrintPreviewDialog::paintRequested,
                 this,&MainWindow::printPreview);

   preview.exec();
}
void MainWindow::createPdf(){
    QString fileName = QFileDialog::getSaveFileName(this, tr("导出PDF文件"), QString(), "*.pdf");
   if (!fileName.isEmpty()) {

       // 如果文件后缀为空，则默认使用.pdf
       if (QFileInfo(fileName).suffix().isEmpty())
           fileName.append(".pdf");
       QPrinter printer;
       // 指定输出格式为pdf
       printer.setOutputFormat(QPrinter::PdfFormat);
       printer.setOutputFileName(fileName);
       ui->textEdit->print(&printer);
   }
}
void MainWindow::printPreview(QPrinter *printer){
    ui->textEdit->print(printer);
}
void MainWindow::onDisconnected(){
    qsTimer->start(3000);
    qDebug()<<"websocket is disconnected";
}
void MainWindow::onTextReceived(QString msg){
    ui->text_socket->append(msg);
    qDebug()<<"收到消息:"<<msg;
}
void MainWindow::onConnected(){
    qsTimer->stop();
    qDebug()<<"websocket is connected";
}
void MainWindow::reconnect(){
    qDebug()<<"websocket reconnected";
    ui->text_socket->append("重新连接 WebSocket!!");
    qwebSocket->abort();
    qwebSocket->open(QUrl("ws://localhost:8080/websocket/2"));
}

void MainWindow::updLable(){
    static int st = 0;
    ui->label_thread->setText(QString("等待线程完成修改:%1").arg(st++));
}

void MainWindow::mtRun(){
    //设置线程运行状态
    myThread->setFlag(false);
    qDebug()<<"主线程号:"<<QThread::currentThreadId();

    qThread->quit();
    qThread->wait();
}

void MainWindow::dealTimeout(){
    if(timer->isActive()){
        static int sec = 1;
        sec++;
        ui->label_timeout->setText(QString("<center><h1>QTimer定时器：%1</h1></center>").arg(sec++));
        if(sec==31){
            timer->stop();//停止定时器
        }
    }
}

void MainWindow::on_btn_qdxc_clicked()
{
      myThread->start();
}

void MainWindow::on_btn_send_clicked()
{
    QString str = ui->edit_send->text();
    ui->text_socket->append(str);
    qwebSocket->sendTextMessage(QString("{toUserId:%1}").arg(str));
}

void MainWindow::on_btn_ws_select_clicked()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    QString url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=%1";
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url.arg(ui->edit_ws_select->text())));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("text/xml; charset=utf-8;"));
    QNetworkReply *reply =  manager->get(requestInfo);

    //添加事件循环机制，返回后再运行后面的
    QEventLoop eventLoop;
    connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec();
    //错误处理
    if (reply->error() == QNetworkReply::NoError){
        qDebug() << "request Http NoError";
    }else{
        qDebug()<<"request Http handle errors";
        QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        qDebug( "request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error());
        qDebug(qPrintable(reply->errorString()));
    }
    //请求返回的结果
    QByteArray responseByte = reply->readAll();
    qDebug() << QString(responseByte);

    QStandardItemModel *ItemModel = new QStandardItemModel(this);

    //解析xml
    QXmlStreamReader reader(responseByte);
    while (!reader.atEnd()){
       if(reader.isStartElement() && reader.name() == "string"){
           reader.readNext();
           if(reader.atEnd()){
               continue;
           }
           if(reader.isCharacters()){
               QString resultCode = reader.text().toString();
               qDebug()<<resultCode<<"\n";

               QStandardItem *item = new QStandardItem(resultCode);
               ItemModel->appendRow(item);
           }

       }
       reader.readNext();
   }
   ui->listView->setModel(ItemModel);
}

void MainWindow::on_btn_dp_clicked()
{
    handler->print();
}

void MainWindow::on_btn_dpyl_clicked()
{
    handler->setPage(view->page());
    handler->printPreview();
}

void MainWindow::on_menu_quit_triggered()
{
    this->hide();
    login->show();
}

void MainWindow::on_pushButton_clicked()
{
    QString str = ui->edit_web->text();
    QString str1 = str.mid(0,4);

    if(str1 == QString::fromLocal8Bit("http")){
        view->setUrl(QUrl(str));
    }else{
        view->setUrl(QString("http://www.baidu.com/s?wd=%1").arg(str));
    }
    view->resize(1024, 750);
    view->show();
    qDebug()<<str1;
}
